<template>
  <a-modal v-model="visible" :footer="null" @cancel="cancel" :closable="false" dialogClass="loginModal" width="700px">
    <h4 class="titleH4">志愿者认证</h4>
    <div class="formData">
      <a-row class="item">
        <div class="label">身份证</div>
        <div class="content">
          <div style="display:inline-block;width:140px;margin-right:20px;">
            <a-upload
              name="filecontent"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              action="/api/upload/img"
              :before-upload="beforeUpload"
              @change="handleChange($event,'positiveimg')"
            >
              <img style="width:200px;height:102px;" v-if="positiveimg" :src="imageWebUrl+positiveimg" alt="avatar" />
              <div v-else>
                <img style="width:200px;" src="@/assets/image/imageIdNumber.png" alt="image">
              </div>
            </a-upload>
            <p style="text-align: center;font-size: 12px;color: #999;width:210px;">身份证正面</p>
          </div>
          <div style="display:inline-block;width:140px;margin-left:70px;">
            <a-upload
              name="filecontent"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              action="/api/upload/img"
              :before-upload="beforeUpload"
              @change="handleChange($event,'otherSideimg')"
            >
              <img style="width:200px;height:102px;" v-if="otherSideimg" :src="imageWebUrl+otherSideimg" alt="avatar" />
              <div v-else>
                <img style="width:200px;" src="@/assets/image/imageIdNumber.png" alt="image">
              </div>
            </a-upload>
            <p style="text-align: center;font-size: 12px;color: #999;width:210px;">身份证反面</p>
          </div>
        </div>
      </a-row>
      <a-row>
        <a-col :span="11" class="item">
          <div class="label">姓名</div>
          <div class="content">
            <a-input size="large" v-model="name" placeholder="请输入姓名" />
          </div>
        </a-col>
        <a-col :span="11" class="item" :offset="2">
          <div class="label">身份证号</div>
          <div class="content">
            <a-input size="large" v-model="idCode" placeholder="请输入身份证号" />
          </div>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" class="item">
          <div class="label">志愿服务经历（选填）</div>
          <div class="content">
            <a-textarea
              v-model="activeMsg"
              :maxLength="200"
              placeholder="简单描述您参与过的志愿服务活动、获得的志愿证书等（200字以内）"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </div>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" class="item">
          <div class="content">
            <p style="font-size:13px;line-height:18px;color:#999999;padding:24px 100px 0;">
              <span style="color:#CA0000;">注</span>：成功认证信息后，您即可成为平台的一名志愿者，更好地服务残障人士，为残疾人公益事业贡献自己的一份爱心。
            </p>
          </div>
        </a-col>
      </a-row>
    </div>
    <!-- 操作 -->
    <div class="operation">
      <a-button size="large" style="margin-right:50px;" @click="visible = false">取消</a-button>
      <a-button size="large" type="primary" @click="authentic">认证</a-button>
    </div>
    <a-modal v-model="successvisible" :maskClosable="false" :closable="false">
      <template #title>
        <a-icon style="color:#FFBE37;" type="info-circle" />
        <span style="display:inline-block;margin-left:10px;color:#333333;">提示信息</span>
      </template>
      <template #footer>
        <a-button size="large" type="primary" @click="hideModal">确认</a-button>
      </template>
      <p style="color:#333333;font-size:18px;line-height:25px;margin-bottom:32px;">恭喜您成功认证为平台志愿者，为您提供了各项便利服务，快去看看吧～</p>
      <p style="color:#333333;font-weight:bold;font-size:14px;line-height:20px;">您可以为残疾人提供哪方面的服务呢（可多选）</p>
      <a-checkbox-group @change="onChange">
        <a-row>
          <a-col :span="6">
            <a-checkbox value="1">
              康复服务
            </a-checkbox>
          </a-col>
          <a-col :span="6">
            <a-checkbox value="2">
              安置服务
            </a-checkbox>
          </a-col>
          <a-col :span="6">
            <a-checkbox value="3">
              生活服务
            </a-checkbox>
          </a-col>
          <a-col :span="6">
            <a-checkbox value="4">
              教育服务
            </a-checkbox>
          </a-col>
          <a-col :span="6">
            <a-checkbox value="5">
              就业服务
            </a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-modal>
  </a-modal>
</template>

<script>
function isIdCard(idCard) {
	// 15位和18位身份证号码的正则表达式
	var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;

	// 如果通过该验证，说明身份证格式正确，但准确性还需计算
	if (regIdCard.test(idCard)) {
		if (idCard.length == 18) {
			var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10,
					5, 8, 4, 2); // 将前17位加权因子保存在数组里
			var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); // 这是除以11后，可能产生的11位余数、验证码，也保存成数组
			var idCardWiSum = 0; // 用来保存前17位各自乖以加权因子后的总和
			for (var i = 0; i < 17; i++) {
				idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
			}

			var idCardMod = idCardWiSum % 11;// 计算出校验码所在数组的位置
			var idCardLast = idCard.substring(17);// 得到最后一位身份证号码

			// 如果等于2，则说明校验码是10，身份证号码最后一位应该是X
			if (idCardMod == 2) {
				if (idCardLast == "X" || idCardLast == "x") {
					//alert("恭喜通过验证啦！");
					return true;
				} else {
					//alert("身份证号码错误！");
					return false;
				}
			} else {
				// 用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
				if (idCardLast == idCardY[idCardMod]) {
					//alert("恭喜通过验证啦！");
					return true;
				} else {
					//alert("身份证号码错误！");
					return false;
				}
			}
		}else{
			return true;
		}
	} else {
		//alert("身份证格式不正确!");
		return false;
	}
}
export default {
  data(){
    return{
      visible: false,
      successvisible:false,
      positiveimg:"", // 身份证正面
      otherSideimg:"", // 身份证反面
      name:"", //姓名
      idCode:"", // 身份证号
      activeMsg:"", //志愿活动说明
      voluntAuthServer:[]
    }
  },
  methods:{
    // 可供服务选中
    onChange(checkedValues) {
      this.voluntAuthServer = checkedValues;
    },
    // 认证成功点击取消
    closemodel(){
      if(this.$route.fullPath == "/personalCenter/information"){
        this.$emit('getUserInfo')
        this.$emit('clearflag')
        this.successvisible = false;
      }else{
        this.successvisible = false;
        this.$router.push("/personalCenter/information")
      }
    },
    // 认证成功点击确认
    hideModal(){
      let str;
      if(this.voluntAuthServer.length){
        str = this.voluntAuthServer.join(",");
      } 
      this.$ajax({
        url:"user/userinfo/edit",
        method:"post",
        params:{
          voluntAuthServer:str
        }
      }).then(res=>{
        if(this.$route.fullPath == "/personalCenter/information"){
          this.$emit('getUserInfo')
          this.$emit('clearflag')
          this.successvisible = false;
          this.visible = false;
        }else{
          this.$router.push("/personalCenter/information")
          this.successvisible = false;
          this.visible = false;
        }
      })
    },
    // 弹框关闭清空状态
    cancel(){
      this.name = "";
      this.idCode = "";
      this.activeMsg = "";
      this.positiveimg = "";
      this.otherSideimg = "";
    },
    // 图片上传
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png" || file.type === "image/jpg";
      if (!isJpgOrPng) {
        this.$message.error("请上传png、jpeg、jpg格式的头像!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传的图片最大为2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    handleChange(info,e) {
      if(info.file.status == 'done' && info.fileList && info.fileList[info.fileList.length-1].response.code == 200){
        this[e] = info.fileList[info.fileList.length-1].response.data;
        // console.log(this[e])
      }else if(info.file.status == 'done' && info.fileList && info.fileList[info.fileList.length-1].response.code != 200){
        this.$message.error(info.fileList[info.fileList.length-1].response.msg)
      }
    },
    // 志愿者认证
    authentic(){
      if(!this.name){
        this.$message.error('请输入姓名')
      }else if(!this.idCode){
        this.$message.error('请输入身份证号')
      }else if(!isIdCard(this.idCode)){
        this.$message.error('请输入正确的身份证号')
      }else if(!this.positiveimg){
        this.$message.error('请上传身份证正面照片')
      }else if(!this.otherSideimg){
        this.$message.error('请上传身份证反面照片')
      }else{
        let userImageJson = [];
        // 身份证正面
        userImageJson.push({
          imgPath:this.positiveimg,
          imgSubType:1,
          imgType:1
        })
        // 身份证反面s
        userImageJson.push({
          imgPath:this.otherSideimg,
          imgSubType:2,
          imgType:1
        })
        this.$ajax({
          url:"/user/userinfo/user/authentic",
          method:"post",
          params:{
            name:this.name,
            idNo:this.idCode,
            voluntAuthFlag:"Y",
            voluntAuthDesc:this.activeMsg,
            userImageJson:JSON.stringify(userImageJson)
          }
        }).then((res)=>{
          if(res.code == 200){
            this.$store.commit('changeroleType',3);
            this.successvisible = true;
          }else{
            this.info(res.msg);
          }
        })
      }
    },
    info(e) {
      const h = this.$createElement;
      this.$info({
        title: '提示信息',
        content: h('div', {}, [
          h('p', e),
        ]),
        onOk() {},
      });
    },
  },
  created(){
  }
}
</script>

<style lang="less" scoped>
/deep/.ant-col-6{
  margin-top: 13px;
}
/deep/.loginModal{
  .ant-modal-body{
    padding: 38px !important;
    padding-bottom: 48px !important;
  }
  .titleH4{
    font-size: 20px;
    line-height: 28px;
    text-align: center;
  }
  .item{
    .label{
      padding-top: 24px;
      padding-bottom: 16px;
      &::after{
        content: '：';
      }
    }
  }
  .operation{
    text-align: center;
    margin-top: 48px;
    button{
      width: 110px;
    }
  }
}
</style>
